/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化通用类
 *
 * @author SoChishun
 * @version 1.0 2016-5-17
 * @see http://www.blogjava.net/sxyx2008/archive/2009/11/09/301663.html
 */
public class SerializableUtil {

    /**
     * 将对象序列化到磁盘文件中(Stream)
     *
     * @param o
     * @param filename
     * @throws Exception
     */
    public static void writeObject(Object o, String filename) throws Exception {
        File f = new File(filename);
        if (f.exists()) {
            f.delete();
        }
        if (!f.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录  
            System.out.println("目标文件所在目录不存在，准备创建它！");
            if (!f.getParentFile().mkdirs()) {
                System.out.println("创建目标文件所在目录失败！");
                return;
            }
        }

        FileOutputStream os = new FileOutputStream(f);
        //ObjectOutputStream 核心类
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(o);
        oos.close();
        os.close();
    }

    /**
     * 反序列化,将磁盘文件转化为对象
     *
     * @param <T>
     * @param filename
     * @return
     * @throws Exception
     * @version 1.0 2016-5-17
     */
    public static <T> T readObject(String filename) throws Exception {
        File f = new File(filename);
        if (!f.exists()) {
            return null;
        }
        InputStream is = new FileInputStream(f);
        //ObjectOutputStream 核心类
        ObjectInputStream ois = new ObjectInputStream(is);
        return (T) ois.readObject();
    }
}
